package com.zlq.cn;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPOutputStream;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class SSHAgent {
    private Logger log = LoggerFactory.getLogger(getClass());
    private Connection connection;

    public void initSession(String hostName, String userName, String passwd) {
        try {
            connection = new Connection(hostName);
            connection.connect();
            boolean authenticateWithPassword = false;
            authenticateWithPassword = connection.authenticateWithPassword(userName, passwd);
            if (!authenticateWithPassword) {
                throw new RuntimeException("Authentication failed. Please check hostName, userName and passwd");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Why can't I execute several commands in one single session?
     * <p>
     * If you use Session.execCommand(), then you indeed can only execute only one command per session. This is not a restriction of the library, but rather an enforcement by the underlying SSH-2 protocol (a Session object models the underlying SSH-2 session).
     * <p>
     * There are several solutions:
     * <p>
     * Simple: Execute several commands in one batch, e.g., something like Session.execCommand("echo Hello && echo again").
     * Simple: The intended way: simply open a new session for each command - once you have opened a connection, you can ask for as many sessions as you want, they are only a "virtual" construct.
     * Advanced: Don't use Session.execCommand(), but rather aquire a shell with Session.startShell().
     *
     * @param command
     * @return
     * @throws IOException
     */

    public String execCommand(String command, Object... args) throws IOException {
        Session session = connection.openSession();
        session.execCommand(String.format(command, args), StandardCharsets.UTF_8.toString());
        InputStream streamGobbler = new StreamGobbler(session.getStdout());
        String result = processStdout(streamGobbler);
        IOUtils.closeQuietly(streamGobbler);
        session.close();
        return result;
    }

    private static String processStdout(InputStream in) {
        InputStream stdout = new StreamGobbler(in);
        StringBuilder buffer = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 远程传输单个文件
     *
     * @param localFile
     * @param remoteTargetDirectory
     * @throws IOException
     */

    public void transferFile(String localFile, String remoteTargetDirectory) throws IOException {
        File file = new File(localFile);
        if (file.isDirectory()) {
            throw new RuntimeException(localFile + "  is not a file");
        }
        String fileName = file.getName();
        //execCommand("cd " + remoteTargetDirectory + ";rm " + fileName + "; touch " + fileName);

        SCPClient sCPClient = connection.createSCPClient();
        SCPOutputStream scpOutputStream = sCPClient.put(fileName, file.length(), remoteTargetDirectory, "7777");
        FileInputStream inputStream = new FileInputStream(file);
        IOUtils.copy(inputStream, scpOutputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(scpOutputStream);
//        String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
//        scpOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
//        scpOutputStream.flush();
//        IOUtils.closeQuietly(scpOutputStream);
    }

    /**
     * 传输整个目录
     *
     * @param localDirectory
     * @param remoteTargetDirectory
     * @throws IOException
     */
    public void transferDirectory(String localDirectory, String remoteTargetDirectory) throws IOException {
        File dir = new File(localDirectory);
        if (!dir.isDirectory()) {
            throw new RuntimeException(localDirectory + " is not directory");
        }

        String[] files = dir.list();
        for (String file : files) {
            if (file.startsWith(".")) {
                continue;
            }
            String fullName = localDirectory + "/" + file;
            if (new File(fullName).isDirectory()) {
                String rdir = remoteTargetDirectory + "/" + file;
                execCommand("mkdir -p " + remoteTargetDirectory + "/" + file);
                transferDirectory(fullName, rdir);
            } else {
                transferFile(fullName, remoteTargetDirectory);
            }
        }

    }

    public void close() {
        connection.close();
    }
}
